#!/usr/bin/python
# -*- coding: UTF-8 -*-

from pymongo import MongoClient
import json
import sys

class MongoDriver():
    def __init__(self, db_charset = 'utf8'):
        self.config         = None
        self.mongo_client   = None
        self.db             = None
        self.collect_names  = None

        try:
            self.mongo_client = self.__connectMongo()
        except "InitMongoErr":
            print "connect mongo error, please check config file exists"

        self.db             = self.mongo_client['medicines']
        self.collect_names  = self.config['collection_names']

    def __del__(self):
        self.mongo_client.close()

    def __loadConfig(self):
        try:
            fp = open('./settings.json', 'r')
        except FileOperateError, e:
            print 'open config error'

        config = fp.read()
        config = json.loads(config)

        fp.close()

        return config

    def __connectMongo(self):
        self.config = self.__loadConfig()

        if self.config['mongo_uri']:
            mongo_client = MongoClient(self.config['mongo_uri'])

            return mongo_client
        else:
            raise Exception("InitMongoErr", "Init Mongo Client Error: missing config file")
